[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  26. // import { useRendererSettings } from '~/stores/renderer';
  27. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  28. import type { EditorConfig } from '~/interfaces/editor-settings';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useEditingMarkdown } from '~/stores/editor';
  36. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  37. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  38. import { useRedirectFrom } from '~/stores/page-redirect';
  39. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  40. import {
  41. useEditorMode, useSelectedGrant,
  42. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  43. } from '~/stores/ui';
  44. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  45. import loggerFactory from '~/utils/logger';
  46. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  47. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  48. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  49. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  50. import { BasicLayout } from '../components/Layout/BasicLayout';
  51. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  52. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  53. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  54. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  55. import {
  56. useCurrentUser,
  57. useIsLatestRevision,
  58. useIsForbidden, useIsNotFound, useIsSharedUser,
  59. useIsEnabledStaleNotification, useIsIdenticalPath,
  60. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  61. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  62. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  63. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  64. useIsSlackConfigured, useRendererConfig,
  65. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  66. } from '../stores/context';
  67. import {
  68. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  69. } from './utils/commons';
  70. // import { useCurrentPageSWR } from '../stores/page';
  71. declare global {
  72. // eslint-disable-next-line vars-on-top, no-var
  73. var globalEmitter: EventEmitter;
  74. }
  75. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  76. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  77. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  78. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  79. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  80. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  81. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  82. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  83. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  84. const logger = loggerFactory('growi:pages:all');
  85. const {
  86. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  87. } = pagePathUtils;
  88. const { removeHeadingSlash } = pathUtils;
  89. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  90. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  91. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  92. {
  93. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  94. return v?.data != null
  95. && v?.data.toObject != null
  96. && v?.meta != null
  97. && isIPageInfoForEntity(v.meta);
  98. },
  99. serialize: (v) => {
  100. return {
  101. data: superjson.stringify(v.data.toObject()),
  102. meta: superjson.stringify(v.meta),
  103. };
  104. },
  105. deserialize: (v) => {
  106. return {
  107. data: superjson.parse(v.data),
  108. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  109. };
  110. },
  111. },
  112. 'IPageToShowRevisionWithMetaTransformer',
  113. );
  114. const IdenticalPathPage = (): JSX.Element => {
  115. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  116. return <IdenticalPathPage />;
  117. };
  118. const PutbackPageModal = (): JSX.Element => {
  119. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  120. return <PutbackPageModal />;
  121. };
  122. type Props = CommonProps & {
  123. currentUser: IUser,
  124. pageWithMeta: IPageToShowRevisionWithMeta | null,
  125. // pageUser?: any,
  126. redirectFrom?: string;
  127. // shareLinkId?: string;
  128. isLatestRevision?: boolean,
  129. isIdenticalPathPage?: boolean,
  130. isForbidden: boolean,
  131. isNotFound: boolean,
  132. isNotCreatablePage: boolean,
  133. // isAbleToDeleteCompletely: boolean,
  134. templateTagData?: string[],
  135. templateBodyData?: string,
  136. isSearchServiceConfigured: boolean,
  137. isSearchServiceReachable: boolean,
  138. isSearchScopeChildrenAsDefault: boolean,
  139. isSlackConfigured: boolean,
  140. // isMailerSetup: boolean,
  141. isAclEnabled: boolean,
  142. // hasSlackConfig: boolean,
  143. drawioUri: string | null,
  144. hackmdUri: string,
  145. noCdn: string,
  146. // highlightJsStyle: string,
  147. isAllReplyShown: boolean,
  148. isContainerFluid: boolean,
  149. editorConfig: EditorConfig,
  150. isEnabledStaleNotification: boolean,
  151. isEnabledAttachTitleHeader: boolean,
  152. // isEnabledLinebreaks: boolean,
  153. // isEnabledLinebreaksInComments: boolean,
  154. adminPreferredIndentSize: number,
  155. isIndentSizeForced: boolean,
  156. disableLinkSharing: boolean,
  157. rendererConfig: RendererConfig,
  158. // UI
  159. userUISettings?: IUserUISettings
  160. // Sidebar
  161. sidebarConfig: ISidebarConfig,
  162. };
  163. const GrowiPage: NextPage<Props> = (props: Props) => {
  164. // const { t } = useTranslation();
  165. const router = useRouter();
  166. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  167. // register global EventEmitter
  168. if (isClient() && window.globalEmitter == null) {
  169. window.globalEmitter = new EventEmitter();
  170. }
  171. // commons
  172. useEditorConfig(props.editorConfig);
  173. useCsrfToken(props.csrfToken);
  174. useCustomizedLogoSrc(props.customizedLogoSrc);
  175. // UserUISettings
  176. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  177. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  178. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  179. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  180. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  181. // page
  182. useIsLatestRevision(props.isLatestRevision);
  183. useIsContainerFluid(props.isContainerFluid);
  184. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  185. useIsForbidden(props.isForbidden);
  186. useIsNotFound(props.isNotFound);
  187. // useIsNotCreatable(props.IsNotCreatable);
  188. useRedirectFrom(props.redirectFrom);
  189. // useShared();
  190. // useShareLinkId(props.shareLinkId);
  191. useIsSharedUser(false); // this page cann't be routed for '/share'
  192. useIsIdenticalPath(false); // TODO: need to initialize from props
  193. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  194. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  195. useIsSearchPage(false);
  196. useTemplateTagData(props.templateTagData);
  197. useTemplateBodyData(props.templateBodyData);
  198. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  199. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  200. useIsSearchServiceReachable(props.isSearchServiceReachable);
  201. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  202. useIsSlackConfigured(props.isSlackConfigured);
  203. // useIsMailerSetup(props.isMailerSetup);
  204. useIsAclEnabled(props.isAclEnabled);
  205. // useHasSlackConfig(props.hasSlackConfig);
  206. useDrawioUri(props.drawioUri);
  207. useHackmdUri(props.hackmdUri);
  208. // useNoCdn(props.noCdn);
  209. useDefaultIndentSize(props.adminPreferredIndentSize);
  210. useIsIndentSizeForced(props.isIndentSizeForced);
  211. useDisableLinkSharing(props.disableLinkSharing);
  212. useRendererConfig(props.rendererConfig);
  213. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  214. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  215. useIsAllReplyShown(props.isAllReplyShown);
  216. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  217. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  218. const { pageWithMeta, userUISettings } = props;
  219. const pageId = pageWithMeta?.data._id;
  220. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  221. useCurrentPageId(pageId ?? null);
  222. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  223. useRemoteRevisionId(pageWithMeta?.data.revision._id);
  224. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  225. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd);
  226. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  227. useCurrentPathname(props.currentPathname);
  228. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  229. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  230. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  231. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  232. const { getClassNamesByEditorMode } = useEditorMode();
  233. useSetupGlobalSocket();
  234. useSetupGlobalSocketForPage(pageId);
  235. const shouldRenderPutbackPageModal = pageWithMeta != null
  236. ? _isTrashPage(pageWithMeta.data.path)
  237. : false;
  238. // sync grant data
  239. useEffect(() => {
  240. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  241. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  242. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  243. useEffect(() => {
  244. const decodedURI = decodeURI(window.location.pathname);
  245. if (isClient() && decodedURI !== props.currentPathname) {
  246. router.replace(props.currentPathname, undefined, { shallow: true });
  247. }
  248. }, [props.currentPathname, router]);
  249. const classNames: string[] = [];
  250. const isSidebar = pagePath === '/Sidebar';
  251. classNames.push(...getClassNamesByEditorMode(isSidebar));
  252. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  253. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  254. ? null
  255. : currentPage.expandContentWidth;
  256. const isContainerFluidDefault = props.isContainerFluid;
  257. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  258. return (
  259. <>
  260. <Head>
  261. {/*
  262. {renderScriptTagByName('drawio-viewer')}
  263. {renderScriptTagByName('highlight-addons')}
  264. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  265. */}
  266. </Head>
  267. <DrawioViewerScript />
  268. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  269. <div className="h-100 d-flex flex-column justify-content-between">
  270. <header className="py-0 position-relative">
  271. <div id="grw-subnav-container">
  272. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  273. </div>
  274. </header>
  275. <div className="d-edit-none">
  276. <GrowiSubNavigationSwitcher />
  277. </div>
  278. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  279. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  280. <div className="flex-grow-1">
  281. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  282. <div id="content-main" className="content-main grw-container-convertible">
  283. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  284. { !props.isIdenticalPathPage && (
  285. <>
  286. <PageAlerts />
  287. { props.isForbidden && <ForbiddenPage /> }
  288. { props.isNotCreatablePage && <NotCreatablePage />}
  289. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  290. {/* <DisplaySwitcher /> */}
  291. <PageStatusAlert />
  292. </>
  293. ) }
  294. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  295. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  296. <div id="revision-toc-content" className="revision-toc-content"></div>
  297. </div>
  298. </div> */}
  299. </div>
  300. </div>
  301. </div>
  302. { !props.isIdenticalPathPage && !props.isNotFound && (
  303. <footer className="footer d-edit-none">
  304. { pageWithMeta != null && pagePath != null && !isTopPagePath && (
  305. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  306. ) }
  307. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  308. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  309. ) }
  310. <CurrentPageContentFooter />
  311. </footer>
  312. )}
  313. <UnsavedAlertDialog />
  314. <DescendantsPageListModal />
  315. <DrawioModal />
  316. <HandsontableModal />
  317. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  318. </div>
  319. </BasicLayout>
  320. </>
  321. );
  322. };
  323. function getPageIdFromPathname(currentPathname: string): string | null {
  324. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  325. }
  326. class MultiplePagesHitsError extends ExtensibleCustomError {
  327. pagePath: string;
  328. constructor(pagePath: string) {
  329. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  330. this.pagePath = pagePath;
  331. }
  332. }
  333. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  334. const { model: mongooseModel } = await import('mongoose');
  335. const req: CrowiRequest = context.req as CrowiRequest;
  336. const { crowi } = req;
  337. const { revisionId } = req.query;
  338. const Page = crowi.model('Page') as PageModel;
  339. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  340. const { pageService } = crowi;
  341. let currentPathname = props.currentPathname;
  342. const pageId = getPageIdFromPathname(currentPathname);
  343. const isPermalink = _isPermalink(currentPathname);
  344. const { user } = req;
  345. if (!isPermalink) {
  346. // check redirects
  347. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  348. if (chains != null) {
  349. // overwrite currentPathname
  350. currentPathname = chains.end.toPath;
  351. props.currentPathname = currentPathname;
  352. // set redirectFrom
  353. props.redirectFrom = chains.start.fromPath;
  354. }
  355. // check whether the specified page path hits to multiple pages
  356. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  357. if (count > 1) {
  358. throw new MultiplePagesHitsError(currentPathname);
  359. }
  360. }
  361. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  362. const page = pageWithMeta?.data as unknown as PageDocument;
  363. // add user to seen users
  364. if (page != null && user != null) {
  365. await page.seen(user);
  366. }
  367. // populate & check if the revision is latest
  368. if (page != null) {
  369. page.initLatestRevisionField(revisionId);
  370. await page.populateDataToShowRevision();
  371. props.isLatestRevision = page.isLatestRevision();
  372. }
  373. if (page == null && user != null) {
  374. const templateData = await Page.findTemplate(props.currentPathname);
  375. if (templateData != null) {
  376. props.templateTagData = templateData.templateTags as string[];
  377. props.templateBodyData = templateData.templateBody as string;
  378. }
  379. }
  380. props.pageWithMeta = pageWithMeta;
  381. }
  382. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  383. const { model: mongooseModel } = await import('mongoose');
  384. const req = context.req as CrowiRequest<IUserHasId & any>;
  385. const { user } = req;
  386. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  387. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  388. if (userUISettings != null) {
  389. props.userUISettings = userUISettings.toObject();
  390. }
  391. }
  392. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  393. const req: CrowiRequest = context.req as CrowiRequest;
  394. const { crowi } = req;
  395. const Page = crowi.model('Page') as PageModel;
  396. const { currentPathname } = props;
  397. const pageId = getPageIdFromPathname(currentPathname);
  398. const isPermalink = _isPermalink(currentPathname);
  399. const page = props.pageWithMeta?.data;
  400. if (props.isIdenticalPathPage) {
  401. // TBD
  402. }
  403. else if (page == null) {
  404. props.isNotFound = true;
  405. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  406. // check the page is forbidden or just does not exist.
  407. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  408. props.isForbidden = count > 0;
  409. }
  410. else {
  411. props.isNotFound = page.isEmpty;
  412. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  413. if (isPermalink && page.isEmpty) {
  414. props.currentPathname = page.path;
  415. }
  416. // /path/to/page ==> /62a88db47fed8b2d94f30000
  417. if (!isPermalink && !page.isEmpty) {
  418. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  419. if (!isToppage) {
  420. props.currentPathname = `/${page._id}`;
  421. }
  422. }
  423. }
  424. }
  425. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  426. // const req: CrowiRequest = context.req as CrowiRequest;
  427. // const { crowi } = req;
  428. // const UserModel = crowi.model('User');
  429. // if (isUserPage(props.currentPagePath)) {
  430. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  431. // if (user != null) {
  432. // props.pageUser = JSON.stringify(user.toObject());
  433. // }
  434. // }
  435. // }
  436. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  437. const req: CrowiRequest = context.req as CrowiRequest;
  438. const { crowi } = req;
  439. const {
  440. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  441. } = crowi;
  442. props.isSearchServiceConfigured = searchService.isConfigured;
  443. props.isSearchServiceReachable = searchService.isReachable;
  444. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  445. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  446. // props.isMailerSetup = mailService.isMailerSetup;
  447. props.isAclEnabled = aclService.isAclEnabled();
  448. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  449. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  450. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  451. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  452. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  453. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  454. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  455. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  456. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  457. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  458. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  459. props.editorConfig = {
  460. upload: {
  461. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  462. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  463. },
  464. };
  465. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  466. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  467. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  468. props.rendererConfig = {
  469. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  470. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  471. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  472. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  473. plantumlUri: process.env.PLANTUML_URI ?? null,
  474. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  475. // XSS Options
  476. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  477. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  478. tagWhiteList: crowi.xssService.getTagWhiteList(),
  479. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  480. };
  481. props.sidebarConfig = {
  482. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  483. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  484. };
  485. }
  486. /**
  487. * for Server Side Translations
  488. * @param context
  489. * @param props
  490. * @param namespacesRequired
  491. */
  492. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  493. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  494. props._nextI18Next = nextI18NextConfig._nextI18Next;
  495. }
  496. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  497. const req = context.req as CrowiRequest<IUserHasId & any>;
  498. const { user } = req;
  499. const result = await getServerSideCommonProps(context);
  500. // check for presence
  501. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  502. if (!('props' in result)) {
  503. throw new Error('invalid getSSP result');
  504. }
  505. const props: Props = result.props as Props;
  506. if (props.redirectDestination != null) {
  507. return {
  508. redirect: {
  509. permanent: false,
  510. destination: props.redirectDestination,
  511. },
  512. };
  513. }
  514. if (user != null) {
  515. props.currentUser = user.toObject();
  516. }
  517. try {
  518. await injectPageData(context, props);
  519. }
  520. catch (err) {
  521. if (err instanceof MultiplePagesHitsError) {
  522. props.isIdenticalPathPage = true;
  523. }
  524. else {
  525. throw err;
  526. }
  527. }
  528. await injectUserUISettings(context, props);
  529. await injectRoutingInformation(context, props);
  530. injectServerConfigurations(context, props);
  531. await injectNextI18NextConfigurations(context, props, ['translation']);
  532. return {
  533. props,
  534. };
  535. };
  536. export default GrowiPage;